<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务事项" prop="workItem">
        <el-input
          v-model="queryParams.workItem"
          placeholder="请输入任务事项"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY年MM月"
          format="YYYY年MM月"
          type="month"
          placeholder="请选择"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['workTask:add']"
          >添加当月任务</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="tableList" border>
      <el-table-column label="序号" type="index" align="center" width="70" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="事项" prop="workItem" align="center" />
      <el-table-column label="指定民警" prop="policeUsers" align="center" />
      <el-table-column label="任务时间" prop="taskMonth" align="center" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            text
            @click="handleDetail(scope.row)"
            v-hasPermi="['workTask:view']"
          >
            查询
          </el-button>

          <el-button
            link
            type="primary"
            text
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workTask:edit']"
          >
            编辑
          </el-button>

          <el-button
            link
            type="primary"
            text
            @click="handleDelete(scope.row)"
            v-hasPermi="['workTask:remove']"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            text
            @click="handlePush(scope.row)"
            v-hasPermi="['workTask:push']"
          >
            推送
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="35vw"
      align-center
      append-to-body
    >
      <el-form
        ref="workTaskRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务事项" prop="workItem" required>
              <el-input
                v-model="form.workItem"
                placeholder="请输入标题"
                type="textarea"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务时间" prop="taskMonth" required>
              <el-date-picker
                v-model="form.taskMonth"
                type="month"
                placeholder="请选择时间"
                format="YYYY年MM月"
                value-format="YYYY年MM月"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="指定民警" prop="selectIds" required>
              <el-cascader
                v-model="form.selectIds"
                placeholder="请选择民警"
                :options="police_options"
                :props="{ multiple: true }"
                filterable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="当月任务"
      v-model="openDetail"
      width="35vw"
      align-center
      append-to-body
    >
      <el-form ref="detailRef" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务事项：">{{ form.workItem }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务时间：">{{ form.taskMonth }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="指定民警：">
              <div class="flex flex-start flex-r" v-if="form.policeUsers">
                <span
                  v-for="(item, index) in form.policeUsers.split('  ')"
                  :key="index"
                >
                  {{ item }}
                </span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WorkTask">
import {
  listWorkTask,
  addWorkTask,
  updateWorkTask,
  delWorkTask,
  getWorkTaskById,
  pushMessage,
} from "@/api/other/workTask";
import { getPoliceGroup } from "@/api/community/police";

const { proxy } = getCurrentInstance();

const tableList = ref([]);
const open = ref(false);
const openDetail = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const police_options = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createTime: undefined,
    workItem: undefined,
  },
  rules: {
    workItem: [
      { required: true, message: "任务事项不能为空", trigger: "blur" },
    ],
    taskMonth: [
      { required: true, message: "任务时间不能为空", trigger: "blur" },
    ],
    selectIds: [
      { required: true, message: "指定民警不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listWorkTask(queryParams.value).then((response) => {
    const { data } = response;
    tableList.value = data.records ?? [];
    total.value = data.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    workItem: undefined,
    taskMonth: undefined,
    selectIds: undefined,
  };
  proxy.resetForm("workTaskRef");
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getPoliceList();
  open.value = true;
  title.value = "添加当月任务";
}

/** 查询按钮操作 */
function handleDetail(row) {
  getWorkTaskById({ id: row.id }).then((response) => {
    form.value = response.data;
    openDetail.value = true;
  });
}

/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  getPoliceList();
  getWorkTaskById({ id: row.id }).then((response) => {
    form.value = response.data;
    if (response.data.selectVo.length) {
      let arr = [];
      response.data.selectVo.forEach((item) => {
        if (item.workTaskVos.length) {
          item.workTaskVos.forEach((it) => {
            arr.push([it.communityId, it.policeUserId]);
          });
        }
      });
      form.value.selectIds = arr;
    }
    response.data.selectVo;
    open.value = true;
    title.value = "当月任务编辑";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workTaskRef"].validate((valid) => {
    if (valid) {
      form.value.selectIds = form.value.selectIds.map((item) => {
        item = {
          communityId: item[0],
          policeUserId: item[1],
        };
        return item;
      });
      if (form.value.id != undefined) {
        updateWorkTask(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWorkTask(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("确认删除该数据", "删除确认")
    .then(function () {
      return delWorkTask(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 获取民警下拉列表数据 */
function getPoliceList() {
  getPoliceGroup({}).then((response) => {
    const { data } = response;
    if (data.length) {
      police_options.value = data.map((item) => {
        let children = [];
        if (item.policeUserCmtVos.length) {
          item.policeUserCmtVos.forEach((police) => {
            children.push({
              value: police.policeUserId,
              label: police.userName,
            });
          });
        }
        return {
          value: item.communityId,
          label: item.communityName,
          children,
        };
      });
    }
  });
}

/** 关闭按钮 */
function close() {
  openDetail.value = false;
  reset();
}

/** 消息推送按钮 */
function handlePush(row) {
  console.log(row);
  pushMessage({ id: row.id }).then((response) => {
    proxy.$modal.msgSuccess("推送成功");
    getList();
  });
}

getList();
</script>
